package com.example.djgzhiyong.androidlevelup

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View

class DividerItemDecoration(context: Context, private val direction: Int) : RecyclerView.ItemDecoration() {

    private val attrs = intArrayOf(android.R.attr.listDivider)

    private val divider: Drawable

    init {
        val a = context.obtainStyledAttributes(attrs)
        divider = a.getDrawable(0)
        a.recycle()
    }

    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)

        parent?.let {
            if (direction == LinearLayoutManager.HORIZONTAL) {
                drawHorizontal(c!!, it)
            } else {
                drawVertical(c!!, it)
            }
        }
    }

    private fun drawVertical(canvas: Canvas, recyclerView: RecyclerView) {
        val left = recyclerView.paddingLeft
        val right = recyclerView.width - recyclerView.paddingRight
        val childCount = recyclerView.childCount

        for (i in 0 until childCount) {
            val childView = recyclerView.getChildAt(i)
            val layoutParams: RecyclerView.LayoutParams = childView.layoutParams as RecyclerView.LayoutParams
            val top = childView.bottom + layoutParams.bottomMargin
            val bottom = top + divider.intrinsicHeight
            divider.setBounds(left, top, right, bottom)
            divider.draw(canvas)
        }
    }

    private fun drawHorizontal(canvas: Canvas, recyclerView: RecyclerView) {
        val top = recyclerView.paddingTop
        val bottom = recyclerView.height - recyclerView.paddingBottom
        val childCount = recyclerView.childCount
        for (i in 0 until childCount) {
            val child = recyclerView.getChildAt(i)
            val layoutParams: RecyclerView.LayoutParams = child.layoutParams as RecyclerView.LayoutParams
            val left = child.right + layoutParams.rightMargin
            val right = left + divider.intrinsicHeight
            divider.setBounds(left, top, right, bottom)
            divider.draw(canvas)
        }
    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.getItemOffsets(outRect, view, parent, state)
        if (direction == LinearLayoutManager.VERTICAL) {
            outRect?.set(0, 0, 0, divider.intrinsicHeight)
        } else {
            outRect?.set(0, 0, divider.intrinsicHeight, 0)
        }
    }

}